package com.chzu.config.security.service;

import com.chzu.mapper.SysUserMapper;
import com.chzu.pojo.SysMenu;
import com.chzu.pojo.SysUser;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.List;


/**
 * @Author lz
 * @Version 1.0
 * @Company 滁州大健康与养老产业研究院
 * @ClassName UserDetailServiceImpl
 * @Description 实现自定义登录逻辑
 * @Date 2022/01/27 19:15
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 注入用户信息
     * @param value
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String value) throws UsernameNotFoundException {
        SysUser user = sysUserMapper.finByUsername(value);
        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        if(user.isAdmin()) {
            user.setRoles(sysUserMapper.findRoles(null));
            user.setPermissions(sysUserMapper.findPermissions(null));
            // 获取父级菜单
            List<SysMenu> menus = sysUserMapper.findMenus(null);
            // 获取子级菜单
            menus.forEach(item -> item.setChildren(sysUserMapper.findChildrenMenu(item.getId(), null)));
            user.setMenus(menus);
        } else {
            // 非管理员要查询角色信息
            user.setRoles(sysUserMapper.findRoles(user.getId()));
            user.setPermissions(sysUserMapper.findPermissions(user.getId()));
            // 获取父级菜单
            List<SysMenu> menus = sysUserMapper.findMenus(null);
            // 获取子级菜单
            menus.forEach(item -> item.setChildren(sysUserMapper.findChildrenMenu(item.getId(), user.getId())));
            user.setMenus(menus);
        }
        return user;
    }
}
